package internal

import (
	"io/ioutil"
	"os"
	"strconv"
	"strings"
)

// 判断路径是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func IsFile(path string) bool {
	fi, err := os.Stat(path)
	if err != nil {
		return false
	}
	return !fi.IsDir()
}

func FileSize(file *os.File) (int64, error) {
	fi, err := file.Stat()
	if err != nil {
		return 0, err
	}
	return fi.Size(), nil
}

func ScanDir(dir string) []string {
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil
	}
	var names []string
	for _, file := range files {
		names = append(names, dir+string(os.PathSeparator)+file.Name())
	}
	return names
}

func GetFileId(file string) (int, error) {
	prefix := strings.TrimSuffix(file, ".db")
	parts := strings.Split(prefix, "-")
	id, err := strconv.Atoi(parts[len(parts)-1])
	return id, err
}
